//JavaScript
var curentObjectId;
var illustrationList;
var curentObjectIllustrationList;
var illustrationToAddList;
var illustrationToRemoveList;
var divZoneIllustrationsOfObject;
var divZoneIllustration;
var limitImg;

function getIllustrations(){
  var url = 'include/bd/update_illustration_bd.php';
  $.getJSON(url
    ,{type_requete:'get_illustrations'}
    ,gestionReponseIllustration);
}

function getIllustrationsFile(){
  var url = 'include/bd/update_illustration_bd.php';
  $.getJSON(url
    ,{type_requete:'get_illustrations_file'}
    ,gestionReponseIllustrationFile);
}


function addLinkIllustration(idObject, idIllustration, table, nomColonne){
  manageUpdateIllustration(idObject,idIllustration, 'link_illustration', table, nomColonne);
}

function removeLinkIllustration(idObject, idIllustration, table, nomColonne){
  manageUpdateIllustration(idObject,idIllustration, 'remove_illustration', table, nomColonne);
}

function manageUpdateIllustration(idObject, idIllustration, typeRequete, table, nomColonne){
  var url = 'include/bd/update_illustration_bd.php';
    // On fait un appel synchrone car on veut faire une opÚration particuliÞre Ó la fin de l'opÚration
    $.ajax({url:url
          ,type:"GET"
          ,data:{type_requete:typeRequete
              , id_link_obj:idObject
              , id_illustration:idIllustration
              , table:table
              , nom_colonne:nomColonne}
          , async:false
          ,success:gestionReponseUpdateIllustration
    });
}

function addIllustrationToBase(){
  var idInputFile = "idUrlIllustrationFromFile";
  var urlIllustration = $('#idUrlIllustration')[0].value;
  var fileIllustration = $('#'+idInputFile)[0];
  var legendeIllustration = $('#idLegendeIllustration')[0].value;
  var url = "include/bd/update_illustration_bd.php";
  if (legendeIllustration != ""){
    legendeIllustration = htmlentities(legendeIllustration);
    if (fileIllustration != null){
      if (fileIllustration.files[0].fileSize <= 2048000 ){
        // on complÞte l'url dans le but de passer les paramÞtres $_GET
        url += "?"+
          "type_requete=add_illustration"+
          "&illustration_url="+urlIllustration+
          "&illustration_legende="+legendeIllustration+
          "&file_id="+idInputFile;
        // On envoie la requête d'upload
        $.ajaxFileUpload
      	(
      			{
      				url:url,
      				secureuri:false,
      				fileElementId:idInputFile,
      				dataType: 'json',
      				success: gestionReponseAddIllustration,
      				error:function (data, status, e)
      				{
      					alert(e);
      				}
      			}
      	);
      	$('#idLoadImgIllustration').show();
    	}else{
        alert("taille du fichier trop gros, upload limités à 2Mo.");
      }
    }else{
      $.getJSON(url
        ,{type_requete:'add_illustration'
          , illustration_url:urlIllustration
          , illustration_legende:legendeIllustration
          , file_id:'idUrlIllustrationFromFile'}
        ,gestionReponseAddIllustration);
    }
  }else{
    alert("Le Champ 'Légende' est obligatoire.");
  }
}

/**
 * MÚthodes de gestion de la rÚcupÚration des requÛte
 */ 
function gestionReponseIllustration(illustrations){
maListeIllustration = illustrations; //REMOVE
  if (illustrations != null){
    var htmlUL = "<UL ID='carouselUL'>";
    var htmlControl = "<DIV ID='idCarouselToLinkControl' class='jcarousel-control'>";
    for (var i = 0; i < illustrations.length; i++){
      var illustration = illustrations[i];
      illustrationList.push(illustration);
      htmlControl += "<A ID='idImgControl"+illustration.idIllustration+"' HREF='#'>"+(i+1)+"<A>";
      addIllustration(illustration.idIllustration, illustration.url);      
    }
    $("#idIllustrations")[0].options[0].selected = true;
  }
  htmlUL += "</UL>";
  htmlControl += "</DIV>";
  $('#carousselList').hide();
  $('#carousselList').html(htmlControl+htmlUL);
  $('#idCarouselToLinkControl').hide();
  jQuery(document).ready(function() {
    jQuery('#carouselUL').jcarousel({
        vertical:true
        ,size: illustrationList.length
        ,itemLoadCallback: {onBeforeAnimation: carouselItemLoadCallBack}
        ,initCallback: callBackToLink
    });
  });
  
  $('#carousselList').show();       
  $('#idImgToLink').hide();
}

function carouselItemLoadCallBack(carousel, state)
{
    var html = "";
    for (var i = carousel.first; i <= carousel.last; i++) {
        if (carousel.has(i)) {
            continue;
        }

        if (i > illustrationList.length) {
            break;
        }
        var illustration = illustrationList[i-1];
        html = ""+
          "<A HREF='javascript:selectIllustrationToLink("+illustration.idIllustration+",\"caroussel\");' onDblclick='linkIllustration();'  >"+
            "<img src='illustrations/"+illustration.url+"' "+
                      "width='75' height='75' alt='' "+
                      "title='"+illustration.legende+"'/>";
            "</A>";

        carousel.add(i, html);
    }
};



/**
 * MÚthodes de gestion de la rÚcupÚration des requÛte
 */ 

function gestionReponseIllustrationFile(illustrations){
  if (illustrations != null){
    $("#idUrlIllustration").autocompleteArray(illustrations
      , {
        delay:10
        ,matchSubset:true
        , matchContains:true
        , cacheLength:10
      });
  }
}

function gestionReponseUpdateIllustration(reponse){
 
}

function gestionReponseAddIllustration(illustration){

  $('#idLoadImgIllustration').hide();
  
  // On vide les champs correspondants
  $('#idUrlIllustration')[0].value = '';
  $('#idUrlIllustrationFromFile')[0].value = '';
  $('#idLegendeIllustration')[0].value = '';
  addIllustration(illustration.idIllustration, illustration.url);
  //On pense Ó ajouter Ó la liste des illustrations
  illustrationList.push(illustration);
  //on ajoute l'illustration Ó la liste des ajouts
  linkIllustration();
}

function manageAddAndRemoveIllustrations(idObject, table, nomColonne){
//On met Ó jour les ilustrations ajouts et suppressions
  if (illustrationToAddList != null){
    for (var i = 0; i < illustrationToAddList.length; i++){
      var illustration = illustrationToAddList[i];
      var found = false;
      var j = 0;
      // On vÚrifie que l'illustration ne fait pas dÚjÓ parti des illustration
      // de l'objet
      while (!found && (j < curentObjectIllustrationList.length)){
        var illustrationTemp = curentObjectIllustrationList[j];
        found = (illustrationTemp.idIllustration == illustration.idIllustration);
        j++;
      }
      if (!found){
        addLinkIllustration(idObject, illustration.idIllustration, table, nomColonne);
      }
    }
  }
  
  if (illustrationToRemoveList != null){
    for (var i = 0; i < illustrationToRemoveList.length; i++){
      var illustration = illustrationToRemoveList[i];
      removeLinkIllustration(idObject, illustration.idIllustration, table, nomColonne);
    }
  }
}

/**
 * MÚthodes d'Údition graphique
 */ 

function initIllustration(idObject, zoneIllustrationsOfObject, zoneIllustration){
  limitImg = -1;
  curentObjectId = idObject;
  divZoneIllustrationsOfObject = zoneIllustrationsOfObject;
  divZoneIllustration = zoneIllustration;
  illustrationList = new Array();
  curentObjectIllustrationList = new Array();
  illustrationToAddList = new Array();
  illustrationToRemoveList = new Array();
  showZoneIllustation();
  $('#idLoadImgIllustration').hide();
  getIllustrations();
  getIllustrationsFile();
}

function setLimitImg(limit){
  limitImg = limit;
}

function getIllusrationToAddList(){
  return illustrationToAddList;
}

function getIllusrationToRemoveList(){
  return illustrationToRemoveList;
}

function setListIllustrations(illustrations){
 for (var i = 0; i < illustrations.length; i ++){
    var illustration = illustrations[i];
    curentObjectIllustrationList.push(illustration);
    illustrationToAddList.push(illustration);
  }
  showIllustrations();
}

function addIllustration(idIllustration, url){
  var length = $("#idIllustrations")[0].options.length; 
  $("#idIllustrations")[0].options[length]= 
        new Option(url
                    ,idIllustration
                    , false
                    , true);
}

function showIllustrations(){
  var html = "<TABLE>";
  for (var i = 0; i < illustrationToAddList.length; i ++){
    var illustration = illustrationToAddList[i];
    html +=""+
        "<TR>"+
				"<TD WIDTH='200px'>"+illustration.url+"</TD>"+
				"<TD align='left'><A HREF='javascript:removeIllustration("+illustration.idIllustration+");' class='blanc'>Supprimer</A></TD>"+
			  "</TR>";
  }
  html += "</TABLE>";
  $('#'+divZoneIllustrationsOfObject).html(html);
}

function linkIllustration(){
// On doit parcourir la liste des illustration Ó la recherche de la bonne
// illustration mais on doit faire attention Ó ce que l'illustration
// ne soit pas dÚjÓ dans la liste d'ajout. On devra vÚrifier si elle
// fait parti des illustration Ó retirer de faþon Ó la retirer de cette liste
  if (((limitImg != -1) && (illustrationToAddList.length < limitImg))
      || (limitImg == -1)){
    var select = $('#idIllustrations')[0];
    var idIllustration = $('#idIllustrations')[0].value;
    for (var i = 0; i < illustrationList.length; i ++){
      var illustration = illustrationList[i];
      if (illustration.idIllustration == idIllustration){
        var found = false;
        var j = 0;
        while (!found && (j < illustrationToAddList.length)){
          var illustrationTemp = illustrationToAddList[j];
          found = illustrationTemp.idIllustration == idIllustration;
          j ++;
        }
        if (!found){
          illustrationToAddList.push(illustration);
          
          // On recherche dans la liste des retraits
          var newListToRemove = new Array();
          for (var k = 0; k < illustrationToRemoveList.length; k ++){
            var illustrationTemp = illustrationToRemoveList[k];
            if (illustrationTemp.idIllustration != idIllustration){
              newListToRemove.push(illustrationTemp);
            }
          }
          illustrationToRemoveList = newListToRemove;        
        }
        break;
      }
    }
    showIllustrations();
  }else{
    alert("Vous ne pouvez pas ajouter plus de "+limitImg+" image(s).");
  }
}

function removeIllustration(idIllustration){
// On recherche l'illustration Ó retirer,
   for (var i = 0; i < illustrationList.length; i ++){
    var illustration = illustrationList[i];
    if (illustration.idIllustration == idIllustration){
      var found = false;
      var j = 0;
      while (!found && (j < illustrationToRemoveList.length)){
        var illustrationTemp = illustrationToRemoveList[j];
        found = illustrationTemp.idIllustration == idIllustration;
        j ++;
      }
      if (!found){
        illustrationToRemoveList.push(illustration);
        
        // On recherche dans la liste des ajouts
        var newListToAdd = new Array();
        for (var k = 0; k < illustrationToAddList.length; k ++){
          var illustrationTemp = illustrationToAddList[k];
          if (illustrationTemp.idIllustration != idIllustration){
            newListToAdd.push(illustrationTemp);
          }
        }
        illustrationToAddList = newListToAdd;        
      }
      break;
    }
  }
  showIllustrations();
}

function callBackToLink(carousel) {
    jQuery('.jcarousel-control a').bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
        return false;
    });
};


function selectIllustrationToLink(idIllustration, origin){
  var illustration = null;
  var index = 0;
  // On recherche l'image correspondant
  for (var i = 0; i < illustrationList.length; i++){
    var illustrationTemp = illustrationList[i];
    if (illustrationTemp.idIllustration == idIllustration){
      illustration = illustrationTemp;
      index = i + 1;
      break;
    }
  }
  // On met Ó jour l'image 
  if (illustration != null){
    $('#idImgToLink')[0].src = "illustrations/"+illustration.url;
    $('#idImgToLink').show();
    $('#idLegendeImgToLink').html("<B>"+illustration.legende+"</B>");
    
    if (origin == "caroussel"){
      // On sÚlectionne dans la liste l'ÚlÚment correspondant
      var optionList = $('#idIllustrations')[0].options;
      for (var i =0; i < optionList.length; i++){
        var option = optionList[i];
        if (option.value == idIllustration){
          option.selected = true;
          break;
        }
    }
    }else if (origin == "select"){
      $('#idImgControl'+idIllustration).click();
    }
  }
}



function showZoneIllustation(){
    var html = ""+
    "<DIV id='admin_top'>"+
		  "<B>Ajouter une illustration</B>"+
		"</DIV>"+
	  "<DIV id='admin_content_back'>"+
	   "<DIV id='admin_content'>"+
	    "<DIV ALGIN='center'>"+
      "<U><B>Ajouter une illustration disponible sur le site (répertoire illustrations) ou depuis votre machine : </B></U>"+
      "<BR>"+
      "</DIV>"+
			"<FORM method='POST' action='javascript:addIllustrationToBase();'>"+
				"<TABLE WIDTH='100%'>"+
				"<TR>"+
					"<TD WIDTH='200px' valign='top'><B>URL : illustrations/</B></TD>"+
					"<TD><INPUT ID='idUrlIllustration' TYPE='text' NAME='url' SIZE='40'></TD>"+
				"</TR>"+
				"<TR>"+
					"<TD WIDTH='200px' valign='top'><B>OU fichier externe :</B></TD>"+
					"<TD><INPUT ID='idUrlIllustrationFromFile' TYPE='file' NAME='idUrlIllustrationFromFile' SIZE='40' ENCTYPE='multipart/form-data'></TD>"+
					"<TD><IMG ID='idLoadImgIllustration' SRC='images/loading.gif' ALIGN='left'></TD>"+
				"</TR>"+
				"<TR>"+
					"<TD WIDTH='200px' valign='top'><B>Légende :</B></TD>"+
					"<TD><INPUT ID='idLegendeIllustration' TYPE='text' NAME='legende' SIZE='40'></TD>"+
				"</TR>"+
				"<TR><TD colspan=2 align='center'>"+
				"<BR><INPUT TYPE='Submit' Value='Ajouter et lier'><BR><BR>"+
				"</TD></TR>"+
				"</TABLE>"+
			"</FORM>"+
			"<HR width='600px'><BR>"+
			"<P ALGIN='center'>"+
      "<U><B>Ajouter une illustration déjà enregistrée sur le site : </B></U>"+
      "<BR>"+
      "</P>"+
			"<FORM method='POST' action='javascript:linkIllustration();'>"+
				"<TABLE WIDTH='100%'>"+
				"<TR>"+
					"<TD WIDTH='200px' valign='top'><B>Images existantes :</B></TD>"+
					"<TD><SELECT ID='idIllustrations' onChange='selectIllustrationToLink(this.value,\"select\");' NAME='id_ill'>"+
					"</SELECT>"+
					"</TD>"+
				"</TR>"+			
				"<TR><TD colspan=2 align='center'>"+
				"<BR><INPUT TYPE='Submit' Value='Lier'><BR><BR>"+
				"</TD></TR>"+
				"</TABLE>"+
			"</FORM>"+
			"<TABLE WIDTH='100%'>"+
  			"<TR>"+
    			"<TD ALIGN='center' WIDTH='300px'>"+
    			  "<DIV ID='carousselList' class='jcarousel-skin-tango'>"+
      			"</DIV>"+
    			"</TD>"+
    			"<TD ALIGN='center' WIDTH='500px'>"+
    			 "<IMG ID='idImgToLink' WIDTH='200px' SRC=''>"+
    			 "<DIV ID='idLegendeImgToLink' ALIGN='center'></DIV>"+
    			"</TD>"+
  			"</TR>"+
			"</TABLE>"+
		"</DIV>"+
		"</DIV>"+
	"</TR>"+
	"<DIV id='admin_content_end'></DIV>";
//"</DIV>"+
//"</TD>"+
//"</TABLE>";

  $('#'+divZoneIllustration).html(html);
}
